﻿using AuthCenter.Domain;
using AuthCenter.ErorCode;
using AuthCenter.Infrastructure;
using AuthCenter_API.Read.Applications.Commands.RBAC;
using AuthCenter_API.Read.Dtos;
using MediatR;

namespace AuthCenter_API.Read.Applications.CommandHandlers.RBAC
{
    public class RoleQueryCommandHandler : IRequestHandler<RoleQueryCommand, APIResult<APIPaging<RoleModel>>>
    {
        private readonly IBaseRepository<RoleModel> _roleRepository;

        public RoleQueryCommandHandler(IBaseRepository<RoleModel> roleRepository)
        {
            _roleRepository = roleRepository;
        }

        public async Task<APIResult<APIPaging<RoleModel>>> Handle(RoleQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPaging<RoleModel>> result = new APIResult<APIPaging<RoleModel>>();
            result.Code = APIEnum.QuerySuccess;
            result.Message = APIEnum.QuerySuccess.Desc();

            var m = _roleRepository.GetAll().Where(x => x.IsDel == 0);
            var count = m.Count();
            var page = (int)Math.Ceiling(1.0 * count / request.Size);
            m = m.OrderByDescending(x => x.RoleId).Skip((request.Index - 1) * request.Size).Take(request.Size);
            APIPaging<RoleModel> p = new APIPaging<RoleModel>();
            p.TotalPage = page;
            p.TotalCount = count;
            p.List = m.ToList();
            result.Data = p;
            return await Task.FromResult(result);
        }
    }
}
